package com.star.uc.infras.utils;

import cn.hutool.core.util.RandomUtil;
import com.star.common.core.context.SpringContext;
import com.star.common.kit.lang.StrPoolUtils;
import com.star.uc.contract.constant.UserConstants;
import com.star.uc.contract.constant.UserRedisConstants;
import com.star.uc.contract.enums.UserGeneratorCodeTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author zhouhengzhe
 */
@Slf4j
@Component
public class GenerateCodeUtils {

    /**
     * 生成验证码，放入redis中
     *
     * @param type     1-短信/2-邮箱
     * @param sendType 发送类型 reg
     * @param tenantId 项目ID
     * @param value    手机号/邮箱
     * @return 验证码
     */
    public String generateCode(Integer type, String sendType, String tenantId, String value) {
        String code = String.valueOf(RandomUtil.randomInt(100000, 999999));
        if (UserGeneratorCodeTypeEnum.PHONE.getCode().equals(type)) {
            //短信验证码//sdk:user:validate:sms:code:reg:8888:8613650768971
            String smsKey = UserRedisConstants.USER_SMS_VALIDATE_CODE + sendType + StrPoolUtils.COLON + tenantId + StrPoolUtils.COLON + value;
            SpringContext.getBean(RedisUtils.class).set(smsKey, code, UserConstants.USER_VALIDATE_CODE_EXPIRE);
            log.info("{} 短信验证码 -> {}", smsKey, code);
        } else {
            //邮箱验证码
            String emailKey = UserRedisConstants.USER_EMAIL_VALIDATE_CODE + sendType + StrPoolUtils.COLON + tenantId + StrPoolUtils.COLON + value;
            SpringContext.getBean(RedisUtils.class).set(emailKey, code, UserConstants.USER_VALIDATE_CODE_EXPIRE);
            log.info("{} 邮箱验证码 -> {}", emailKey, code);
        }
        return code;
    }

}
